﻿// Decompiled with JetBrains decompiler
// Type: TaleWorlds.MountAndBlade.View.MissionViews.Singleplayer.MissionEntitySelectionUIHandler
// Assembly: TaleWorlds.MountAndBlade.View, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 61152EB8-513B-4D4A-8AC0-0D1465C6CF6C
// Assembly location: D:\steam\steamapps\common\Mount & Blade II Bannerlord\Modules\Native\bin\Win64_Shipping_Client\TaleWorlds.MountAndBlade.View.dll

using System;
using System.Diagnostics;
using TaleWorlds.DotNet;
using TaleWorlds.Engine;
using TaleWorlds.InputSystem;
using TaleWorlds.Library;

#nullable disable
namespace TaleWorlds.MountAndBlade.View.MissionViews.Singleplayer
{
  public class MissionEntitySelectionUIHandler : MissionView
  {
    private Action<GameEntity> onSelect;
    private Action<GameEntity> onHover;

    public MissionEntitySelectionUIHandler(Action<GameEntity> onSelect = null, Action<GameEntity> onHover = null)
    {
      this.onSelect = onSelect;
      this.onHover = onHover;
    }

    public override void OnMissionScreenTick(float dt)
    {
      base.OnMissionScreenTick(dt);
      GameEntity gameEntity = new Lazy<GameEntity>(new Func<GameEntity>(this.GetCollidedEntity)).Value;
      Action<GameEntity> onHover = this.onHover;
      if (onHover != null)
        onHover(gameEntity);
      if (!this.Input.IsKeyReleased(InputKey.LeftMouseButton))
        return;
      Action<GameEntity> onSelect = this.onSelect;
      if (onSelect == null)
        return;
      onSelect(gameEntity);
    }

    private GameEntity GetCollidedEntity()
    {
      Vec3 rayBegin;
      Vec3 rayEnd;
      this.MissionScreen.ScreenPointToWorldRay(this.Input.GetMousePositionRanged(), out rayBegin, out rayEnd);
      using (new TWSharedMutexUpgradeableReadLock(Scene.PhysicsAndRayCastLock))
      {
        if (Mission.Current == null)
          return (GameEntity) null;
        GameEntity collidedEntity;
        Mission.Current.Scene.RayCastForClosestEntityOrTerrainMT(rayBegin, rayEnd, out float _, out collidedEntity, 0.3f);
        while ((NativeObject) collidedEntity != (NativeObject) null && (NativeObject) collidedEntity.Parent != (NativeObject) null)
          collidedEntity = collidedEntity.Parent;
        return collidedEntity;
      }
    }

    public override void OnRemoveBehavior()
    {
      this.onSelect = (Action<GameEntity>) null;
      this.onHover = (Action<GameEntity>) null;
      base.OnRemoveBehavior();
    }

    [Conditional("DEBUG")]
    public void TickDebug()
    {
      GameEntity collidedEntity = this.GetCollidedEntity();
      if ((NativeObject) collidedEntity == (NativeObject) null)
        return;
      string name = collidedEntity.Name;
    }
  }
}
